package org.elip.stewiemaze.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.elip.stewiemaze.server.FormValidator;
import org.elip.stewiemaze.server.services.PlayerService;
import org.elip.stewiemaze.server.services.RegisterPlayerService;
import org.elip.stewiemaze.server.utils.CookieUtils;
import org.elip.stewiemaze.server.utils.MailUtils;
import org.elip.stewiemaze.shared.entities.Player;

public class RegisterPlayerServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Logger logger = Logger.getLogger(RegisterPlayerServlet.class.getName());
		
		logger.fine("Got request from url : " + req.getRequestURL().toString());
		
		handleRegularRegistration(req,resp);
		
	}


	private void handleRegularRegistration(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Logger logger = Logger.getLogger(RegisterPlayerServlet.class.getName());
		
		logger.fine("started handling regular registration request");
		
		PrintWriter out = resp.getWriter();
		
		/* Get registration details from the request */
		String name = req.getParameter("nickname");;
		Long score = Long.parseLong(req.getParameter("score"));;
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		
		logger.fine("request parameters are : name=" + name + " | " + "score=" + score + " | " + "email=" + email + " | " + "password=" + password);
		
		/* Validate the form server side */
		List<String> errors = FormValidator.validateForm(name, email, password);
				
		if (errors.size() == 0) { // no erros, can register
			
			logger.fine("the request has been validated on the server, adding to database");
			
			/* Remove this cookie, it will be replace with the "highscore" cookie */
			CookieUtils.eraseCookie(req, resp, "tempScore");
			
			/* Create a regular player */
			Player player = PlayerService.createPlayer(name, email, password, score, false);
			
			/* Save player to the database, not activated yet */
			RegisterPlayerService.registerPlayer(player);
			
			/* Add cookies so that uppon return to the application the user will be identifeid */
			resp.addCookie(new Cookie("nickname", name));
			resp.addCookie(new Cookie("highscore", score + ""));
			
			if (email.equals("")) { // A player has not registered for notification, no need to send validation mail
				
				logger.fine("added to databse succesfully");
				
				out.println("Congrats, you have registered succesfully");
				out.println("<a href='http://stewiemaze.appspot.com'>Return to game</a>");
			}
			else {
		        try { // A player has registered for notifications, needs to verify the given email
		        	
		        	logger.fine("added to databse succesfully");
		        	logger.fine("sending an activation email to :" + email);
		        	
		        	MailUtils.sendValidationMail(email, name);
		        	out.println("Please verify your account by reading the message we have just sent you");
		        	out.println("<br>");
		        	out.println("After that, click <a href='http://2.stewiemaze.appspot.com'>Here</a> to return to the game");
		        	out.println("<a href='http://stewiemaze.appspot.com'>Return to app</a>");
		        } catch (AddressException e) {
		            throw new ServletException("Sorry, something happened...", e);
		        } catch (MessagingException e) {
		        	throw new ServletException("Sorry, something happened...", e);
		        } catch (UnsupportedEncodingException e) {
		        	throw new ServletException("Sorry, something happened...", e);
				}
			}
		}
		else { // Errors exist in the form, let the user know and offer to return to the application. the users score is saved in the tmpScore cookie
			for (String error : errors) {
				
				logger.fine("request validation failed on the server");
				
				out.println(error);
				out.println("<a href='http://stewiemaze.appspot.com'>Return to game</a>");
			}	
		}
	}
}
